import os
import socket
import time

import requests

import json

from urllib3.exceptions import NewConnectionError

# 获取当前文件路径，拼接json配置文件，生成路径，以供后面使用
path = os.path.dirname(__file__)
json_file_path = path + '/token.json'


# 获取最新token，完成token替换
def get_token():
    url = "http://zeus.corp.hongsong.club/portal/prod/api/login"

    payload = json.dumps({
        "username": "fanchao",
        "password": "fanchao110."
    })
    headers = {
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    token = response.json()['data']['token']

    # 读取token配置文件中的内容
    with open(json_file_path, 'r') as f:
        data = json.load(f)
    # 将获取到的接口的token，写入到data中
    data['token'] = token
    # 将data再次写入token文件，完成token的替换
    with open(json_file_path, 'w') as f1:
        f1.write(json.dumps(data))
    print('token替换完成')


# 调用审核接口，传入需要审核的任务id
def check_approved(taskId):
    url = "http://zeus.corp.hongsong.club/portal/prod/api/approval/approved"

    payload = json.dumps({
        "taskId": taskId,
        "auditStatus": 2,
        "publishType": 2
    })
    headers = {
        'Authorization': token,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)
    # 如果有如下返回，说明token失效，需要替换token文件中的token
    if response.json()['status']['des'] == '认证失效' and response.json()['status']['code'] == 100004:
        get_token()  # 替换token
        print('替换完成，下一次执行生效')


# 获取服务的任务列表，传入多个服务名，将得到的data数据拼接起来返回
def get_Task_List(server_names):
    # 定义请求地址
    url = "http://zeus.corp.hongsong.club/portal/prod/api/deployTask/getTaskList"
    # 定义请求头
    headers = {
        'Authorization': token,
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }
    # 定义存放数据的列表
    datas = []
    # 对入参的服务进行循环处理
    for server_name in server_names:
        # print(server_name)
        # 定义请求体，对服务名遍历
        payload = json.dumps({
            "appCode": server_name,
            "env": "all",
            "startIndex": 0,
            "pageSize": 5
        })
        try:
            # 请求接口
            response = requests.request("POST", url, headers=headers, data=payload)
        except requests.exceptions.RequestException as e:
            print("请求接口发生错误:", e)
        except KeyError as e:
            print("解析JSON数据发生错误:", e)
        except Exception as e:
            print("发生未知错误:", e)
        try:
            # 获取响应中的data
            data = response.json()['data']
            # 利用extend方法，将数据加到datas末尾
            datas.extend(data)
        except Exception as e:  # 报错后兜底逻辑，随便给一个指定的datas。防止程序中断。
            print(e)
            print('------------------------')
            print(response.text)
            datas = [
                {'creator': 'creator_name_test1', 'status': 'DONE', 'env': 'test', 'auditStatus': 2, 'scope': '测试'}]
        time.sleep(0.5)

    # 返回组装好的datas
    return datas


# 处理datas数据，进行审核
def handle_datas_to_examine(datas):
    for i in range(len(datas)):
        # 判断是测试环境并且状态是未审核,且提交人是【xxx，xxx】creator
        # print(datas[i]['status'])
        if (datas[i]['env'] == 'test'
                and datas[i]['status'] == 'PENDING'
                and datas[i]['auditStatus'] == 0
                and datas[i]['creator'] in ['guanyue', 'yuanliang', 'likai', 'wushuang', 'zhangli02', 'panmingwei',
                                            'liujinlei', 'licai', 'yuzhentao', 'wangxing01', 'fuzhongfeng',
                                            'zhangqiang01', 'wangyiyun', 'yangkezhong', 'zhenglin']):
            taskId = datas[i]['taskId']
            creator = datas[i]['creator']
            deployBranch = datas[i]['deployBranch']
            appCode = datas[i]['compileSchema']['appCode']
            scope = datas[i]['scope']

            print(time.strftime('%Y-%m-%d %H:%M:%S'),
                  '=====>准备审批，id是：%s,服务名：%s，分支：%s，提交人：%s，范围：%s' % (
                      taskId, appCode, deployBranch, creator, scope))
            # 执行审核操作
            check_approved(taskId)


if __name__ == '__main__':
    # 需要审批的服务器
    server_list = ['edu-fjkt-h5', 'edu-fengjin-sale-web', 'edu-fengjin-admin-web', 'edu-fengjin-app-service',
                   'edu-fengjin-callback-web', 'fjkt-api-ui-interfaces', 'fjkt-homework-service', 'fjkt-course-service',
                   'fjkt-crm-course-ui-interfaces', 'fjkt-business-course-service', 'edu-fengjin-app-web',
                   'fjkt-uc-user-service', 'fjkt-crm-homework-ui-interfaces', 'edu-fengjin-common-mall-service',
                   'edu-fengjin-mall-service', 'edu-fengjin-bmall-web', 'edu-fengjin-cmall-web',
                   'fjkt-user-gateway-server', 'fjkt-crm-gateway-server', 'edu-fengjin-doraemon-node',
                   'fjkt-business-tag-web', 'fjkt-fe-crm-vidar', 'fjkt-heimdallr', 'business-hs-ios-lite',
                   'business-hs-android-lite', 'edu-fengjin-admin-server', 'fjkt-fe-crm-sales-management',
                   'business-android-sdk-baselib', 'fjkt-h5-topic', 'fjkt-base-activity-service',
                   'fjkt-crm-activity-ui-interfaces', 'edu-fengjin-mall-server', 'fjkt-fe-crm-mall', 'fjkt-fe-crm-base',
                   'business-android-hs-pad' 'edu-fjkt-hybrid', 'business-android-sdk-live', 'fjkt-fe-crm-live',
                   'fjkt-course-user-domain',
                   'fjkt-hs-website-h5', 'fjkt-hs-website', 'business-hs-ios-lite']
    print(len(server_list))
    while True:
        # 获取配置文件中的token
        with open(json_file_path, 'r') as f:
            data = json.load(f)
        token = data['token']
        # 执行获取审批任务列表数据的方法
        datas = get_Task_List(server_list)
        # 执行处理数据并审批的方法
        handle_datas_to_examine(datas)
        # 等待
        time.sleep(10)
        print(time.strftime('%Y-%m-%d %H:%M:%S'))
        # print(1)

# {"status":{"code":100004,"des":"认证失效"}}
# {"status":{"code":250003,"des":"任务165356的状态不支持审批功能"},"data":{}}
